package util;

import com.github.pagehelper.PageInfo;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * list 分页工具类：在list包含有子list去情况下只分页大的list而不去分页子list
 * 以前使用的 PageHelper.startPage(pageNum, pageSize);不满足list中包含有list的分页情况，会产生将子list进行分页的效果
 * <p>
 * 需要先导入jar包
 * <dependency>
 *      <groupId>com.github.pagehelper</groupId>
 *      <artifactId>pagehelper-spring-boot-starter</artifactId>
 *      <version>1.2.10</version>
 * </dependency>
 */
public class PageInfoUtil {
    /**
     * @param list     需要进行分页的list
     * @param pageNum  分页起始页面数
     * @param pageSize 分页大小
     */
    public static <T> PageInfo<T> listToPageInfo(List<T> list, Integer pageNum, Integer pageSize) {
        pageNum = null == pageNum ? 1 : pageNum;
        pageSize = null == pageSize ? 10 : pageSize;
        int pageNo = (pageNum - 1) * pageSize;
        int total = 0;
        int pages = 0;
        PageInfo<T> pageInfo = null;
        if (!CollectionUtils.isEmpty(list)) {
            total = list.size();
            pages = (total / pageSize) + (total % pageSize == 0 ? 0 : 1);
            if (pageNo + pageSize > total) {
                if (pageNo > total) {
                    list = new ArrayList<>();
                } else {
                    list = list.subList(pageNo, total);
                }
            } else {
                list = list.subList(pageNo, pageNo + pageSize);
            }
            pageInfo = new PageInfo<T>(list);
        } else {
            pageInfo = new PageInfo<T>(new ArrayList<>());
        }
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(total);
        pageInfo.setPages(pages);
        pageInfo.setPrePage(pageNum - 1);
        pageInfo.setNextPage(pageNum + 1);
        pageInfo.setIsFirstPage(pageNum == 1);
        pageInfo.setIsLastPage(pageNum >= pages);
        pageInfo.setHasPreviousPage(pageNum != 1);
        pageInfo.setHasNextPage(pageNum < pages);
        pageInfo.setNavigateFirstPage(1);
        pageInfo.setNavigateLastPage(pages);
        int[] nums = new int[pages];
        for (int i = 0; i < pages; i++) {
            nums[i] = i + 1;
        }
        pageInfo.setNavigatepageNums(nums);
        return pageInfo;
    }
}
